package cn.com.pajx.pajx_smart_platform.api;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import cn.com.pajx.pajx_smart_platform.tools.ToastUtil;
import retrofit2.HttpException;

/**
 * create by ruancw on 2023/04/03
 * 网络请求异常处理类
 */

class ExceptionHandle {
    private static final int UNAUTHORIZED = 401;
    private static final int FORBIDDEN = 403;
    private static final int NOT_FOUND = 404;
    private static final int REQUEST_TIMEOUT = 408;
    private static final int INTERNAL_SERVER_ERROR = 500;
    private static final int BAD_GATEWAY = 502;
    private static final int SERVICE_UNAVAILABLE = 503;
    private static final int GATEWAY_TIMEOUT = 504;

    static void handleException(Throwable e) {
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            switch (httpException.code()) {
                case UNAUTHORIZED:
                case FORBIDDEN:
                case NOT_FOUND:
                case REQUEST_TIMEOUT:
                case GATEWAY_TIMEOUT:
                case INTERNAL_SERVER_ERROR:
                case BAD_GATEWAY:
                case SERVICE_UNAVAILABLE:
                default:
                    ToastUtil.toast("服务器连接失败，请稍后再试");
                    break;
            }
        } else if (e instanceof RuntimeException) {
            ToastUtil.toast("RuntimeException");
        } else if (e instanceof JSONException) {
            ToastUtil.toast("数据解析错误");
        } else if (e instanceof ConnectException) {
            ToastUtil.toast("服务器连接失败");
        } else if (e instanceof javax.net.ssl.SSLHandshakeException) {
            ToastUtil.toast("证书验证失败");
        } else if (e instanceof SocketTimeoutException) {
            ToastUtil.toast("连接超时");
        } else {
            ToastUtil.toast("网路连接失败");
        }
    }
}
